<?php

   # Repository path:    $HeadURL: http://aberystwythvoyager.googlecode.com/svn/iGoogle/tags/Current/doSearch.php $
   # Last committed:     $Revision: 52 $
   # Last changed by:    $Author: andrewisherwood $
   # Last changed date:  $Date: 2009-12-11 10:36:33 +0000 (Fri, 11 Dec 2009) $
   # ID:                 $Id: doSearch.php 52 2009-12-11 10:36:33Z andrewisherwood $

   # We have to do this is two steps, first we initialise the search with
   # a POST request to SearchService. We disregard the results from this
   # as we're using SearchResultsService to obtain our results, SearchResultsService
   # allows a results pointer to be set. We grab the JSESSIONID header from
   # the response from SearchService as this identifies our search session
   # and enables SearchResultsService to furnish us with the correct results
   # when we send it back with our request.
   
   # Results per page
   $resPerPage=10;
   
   # Get the search term(s)
   $searchParam=$_GET['searchParam'];
   
   # Get the session ID
   $sessionid=(isset($_GET['sid']) && $_GET['sid']!="0") ? $_GET['sid'] : "";
   
   # Get the user's preferred language
   $lang=(isset($_GET['lang']) && strlen($_GET['lang']) > 0) ? $_GET['lang'] : "en";
   
   # Get the user's country
   $country=(isset($_GET['country']) && strlen($_GET['country']) > 0) ? $_GET['country'] : "ALL";
   
   # Get the starting point
   $start=(isset($_GET['start']) && strlen($_GET['start']) > 0) ? $_GET['start'] : 0;
   
   # Get the total number of hits
   $totalHits =(isset($_GET['total']) && strlen($_GET['total']) > 0) ? $_GET['total'] : "";
   
   $nextStart=$start+$resPerPage;
   
   $txt="";
   
   # Get the iGoogle message bundle for the language we're using
   $msgB_main=$lang."_".$country.".xml"; # Our first choice, using the client's country and lanugage
   $msgB_bk1=$lang."_ALL.xml"; # Second choice, correct language from any country
   $msgB_bk2="ALL_ALL.xml"; # Fallback position, English regardless of where they're from
   
   # If there is not an exact match for our desired
   # message bundle
   if (!file_exists($msgB_main)) {
      # See if there is one for this language in ALL countries
      if (!file_exists($msgB_bk1)) {
         # If there is no fallback message bundle
         # for all languages and countries, there's no
         # hope
         if (!file_exists($msgB_bk2)) {
            die;
         }
      } else {
         $txt=file_get_contents($msgB_bk1);
      }
   } else {
      $txt=file_get_contents($msgB_main);
   }
      
   # Grab the message bundle and messages
   $txtXML=simplexml_load_string($txt);
   $moreresults=$txtXML->xpath("//msg[@name='moreresults']");
   $results1=$txtXML->xpath("//msg[@name='results1']");
   $results2=$txtXML->xpath("//msg[@name='results2']");
   
   # The Voyager URL
   $server="voyager.aber.ac.uk";
   
   # The webservice port
   $port="7014";
   
   # A flag to check whether this is a
   # new session
   $newSession=0;
   
   # We don't have an existing sessionid so we
   # need to get one
   if (strlen($sessionid) < 1) {
      
      $newSession=1;
      
      # The XML we're sending in the POST to SearchService
      $body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
             <ser:serviceParameters xmlns:ser=\"http://www.endinfosys.com/Voyager/serviceParameters\">
                <ser:parameters/>
                <ser:definedParameters xsi:type=\"sear:searchDefinitionType\" xmlns:sear=\"http://www.endinfosys.com/Voyager/search\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
                   <sear:searchComponents>
                      <sear:searchComponent>
                         <sear:searchArg>$searchParam</sear:searchArg>
                         <sear:searchCode>GKEY</sear:searchCode>
                         <sear:searchArgType>AND</sear:searchArgType>
                      </sear:searchComponent>
                   </sear:searchComponents>
                   <sear:maxResultsPerPage>10</sear:maxResultsPerPage>
                   <sear:relevanceFlag>Y</sear:relevanceFlag>
                </ser:definedParameters>
             </ser:serviceParameters>";
   
      # Send the initial request to SearchService to get a sessionid
      $initResp = makePostRequest("SearchService",$body,$server,$port,"");
      
      $foundXML=0;
      $xmlDoc="";
      
      # Get the JSESSIONID cookie value
      # Also put the XML results into a string so we
      # can determine the total number of results
      foreach ($initResp as $initLine) {
         if (preg_match("/JSESSIONID=(.*);/",$initLine,$matches)) {
            $sessionid=$matches[1];
         }
         if ($foundXML==1 || preg_match("/<\?xml/",$initLine)) {
            $xmlDoc.=$initLine;
            $foundXML=1;
         }
      }
      
      # Get the total number of results
      # Load the XML file as a simplexml object
      $xml=simplexml_load_string($xmlDoc);
      
      # Fetch all namespaces
      $namespaces = $xml->getNamespaces(true);
      
      # Register them with their prefixes
      foreach ($namespaces as $prefix => $ns) {
          $xml->registerXPathNamespace($prefix, $ns);
      } 
      
      # Get the total hit count
      $totalHits=$xml->xpath('//sear:totalHits');
      $totalHits=(string)$totalHits[0];
   }
   
   $newBody="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
             <ser:serviceParameters xmlns:ser=\"http://www.endinfosys.com/Voyager/serviceParameters\">
                <ser:parameters>
                   <ser:parameter key=\"searchType\">
                      <ser:value>FIND</ser:value>
                   </ser:parameter>
                   <ser:parameter key=\"resultPointer\">
                      <ser:value>".$start."</ser:value>
                   </ser:parameter>
                   <ser:parameter key=\"maxResultsPerPage\">
                      <ser:value>10</ser:value>
                   </ser:parameter>
                   <ser:parameter key=\"sortBy\">
                      <ser:value>RELEVANCE</ser:value>
                   </ser:parameter>
               </ser:parameters>
             </ser:serviceParameters>";

   # Make the request to get the search results, passing the session id
   $searchResp = makePostRequest("SearchResultsService",$newBody,$server,$port,$sessionid);

   $xmlResponse="";
   $startXML=0;
   foreach ($searchResp as $searchLine) {
      if ($startXML==1 || preg_match("/^<\?xml/",$searchLine)) {
         $xmlResponse.=$searchLine;
         $startXML=1;
      }
   }
   
   # Load the XML file as a simplexml object
   $xml=simplexml_load_string($xmlResponse);
   
   # Fetch all namespaces
   $namespaces = $xml->getNamespaces(true);
   
   # Register them with their prefixes
   foreach ($namespaces as $prefix => $ns) {
       $xml->registerXPathNamespace($prefix, $ns);
   } 
   
   # Print the results
   if ($newSession==1) {
      print "<p id=\"hitCount\">$results1[0] $totalHits $results2[0]</p>";
      print "<ol id=\"results\">";
   }
   foreach ($xml->xpath('//sear:result') as $result) {
      $kids=$result->children('http://www.endinfosys.com/Voyager/search');
      $bibId=$kids->bibId;
      $bibTitle=$kids->bibText1;
      print "<li><a href=\"http://voyager.aber.ac.uk/vwebv/holdingsInfo?bibId=$bibId&sk=$lang\" target=\"_blank\" title=\"$bibTitle\">$bibTitle</a></li>";
   }
   if ($newSession==1) {
      print "</ol>";
   }
   
   # Only print a link to further results if there are more
   if ($totalHits >= $nextStart) {
      print "<p id=\"moreresults\"><a href=\"#\" id=\"morelink\" class=\"${nextStart}_${sessionid}_$totalHits\" title=\"$moreresults[0]\">$moreresults[0]</a></p>";
   }
   
   
   function makePostRequest($service,$xml,$server,$port,$sessionid) {
      # Send the request via POST       
      $contentLength = strlen($xml);
      $fp = fsockopen($server, $port);
      fputs($fp, "POST /vxws/$service HTTP/1.0\r\n");
      fputs($fp, "Host: $server\r\n");
      fputs($fp, "Content-Type: text/xml\r\n");
      # Only include the session id if we've got one
      if (strlen($sessionid)>0) {
         fputs($fp, "Cookie: JSESSIONID=$sessionid\r\n");
      }
      fputs($fp, "Content-Length: $contentLength\r\n");
      fputs($fp, "Connection: close\r\n");
      fputs($fp, "\r\n");
      fputs($fp, $xml);

      $resp=array();      
      # Put the result in an array and send back
      while (!feof($fp)) {
         $line=fgets($fp, 128);
         $resp[]=$line;
      }
      
      return $resp;
   }
   

?>